import { useStore } from '@/store/useStore';
import { ComponentType } from '@/types/component';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import prettier from 'prettier';
import parserBabel from 'prettier/parser-babel';

// 格式化生成的代码
const formatCode = (code: string) => {
  try {
    return prettier.format(code, {
      parser: 'babel',
      plugins: [parserBabel],
      singleQuote: true,
      trailingComma: 'all',
      printWidth: 100,
    });
  } catch (e) {
    console.error('格式化代码失败:', e);
    return code;
  }
};

// 生成组件代码
const generateComponentCode = (component: any, modelMap: Record<string, any>) => {
  let propsString = '';
  for (const [key, value] of Object.entries(component.props)) {
    if (key === 'dataBinding') continue;
    
    if (typeof value === 'string') {
      propsString += `${key}="${value}" `;
    } else {
      propsString += `${key}={${JSON.stringify(value)}} `;
    }
  }
  
  // 处理数据绑定
  let dataHook = '';
  let dataVariable = '';
  if (component.props.dataBinding) {
    const { model, fields } = component.props.dataBinding;
    const modelName = modelMap[model]?.name || model;
    
    switch (component.type) {
      case ComponentType.TABLE:
        dataHook = `const [data, loading, error] = use${modelName}List();\n  `;
        dataVariable = `dataSource={data} `;
        break;
        
      case ComponentType.FORM:
        dataHook = `const [form] = Form.useForm();\n  `;
        break;
        
      default:
        break;
    }
  }

  let componentCode = '';
  switch (component.type) {
    case ComponentType.BUTTON:
      componentCode = `<Button ${propsString}>{${component.props.text || '按钮'}}</Button>`;
      break;
      
    case ComponentType.SEARCH_BAR:
      componentCode = `<Input.Search ${propsString} />`;
      break;
      
    case ComponentType.TABLE:
      const columns = modelMap[component.props.dataBinding?.model]?.fields?.map((field: any) => ({
        title: field.label,
        dataIndex: field.name,
        key: field.name,
      })) || [];
      
      componentCode = `
        <Table 
          ${propsString}
          ${dataVariable}
          columns={${JSON.stringify(columns, null, 2)}}
          loading={loading}
          rowKey="id"
        />
      `;
      break;
      
    case ComponentType.FORM:
      const formItems = modelMap[component.props.dataBinding?.model]?.fields?.map((field: any) => `
        <Form.Item
          label="${field.label}"
          name="${field.name}"
          ${field.required ? 'rules={[{ required: true, message: \'请输入${field.label}\' }]}' : ''}
        >
          <Input />
        </Form.Item>
      `).join('\n        ') || '';
      
      componentCode = `
        <Form ${propsString}>
          ${formItems}
        </Form>
      `;
      break;
      
    case ComponentType.INPUT:
      componentCode = `<Input ${propsString} />`;
      break;
      
    case ComponentType.SELECT:
      componentCode = `
        <Select ${propsString}>
          <Select.Option value="option1">选项1</Select.Option>
          <Select.Option value="option2">选项2</Select.Option>
        </Select>
      `;
      break;
      
    case ComponentType.DATE_PICKER:
      componentCode = `<DatePicker ${propsString} style={{ width: '100%' }} />`;
      break;
      
    default:
      componentCode = `<div>未知组件: ${component.type}</div>`;
  }
  
  return {
    hook: dataHook,
    code: componentCode
  };
};

// 生成页面代码
const generatePageCode = (page: any, modelMap: Record<string, any>) => {
  const imports = new Set<string>();
  imports.add('React');
  
  const hooks: string[] = [];
  const components: string[] = [];
  
  page.components.forEach((comp: any) => {
    const { hook, code } = generateComponentCode(comp, modelMap);
    if (hook) hooks.push(hook);
    components.push(code);
    
    // 添加组件导入
    switch (comp.type) {
      case ComponentType.BUTTON:
        imports.add('Button');
        break;
      case ComponentType.TABLE:
        imports.add('Table');
        break;
      case ComponentType.FORM:
        imports.add('Form');
        imports.add('Input');
        break;
      case ComponentType.SEARCH_BAR:
      case ComponentType.INPUT:
        imports.add('Input');
        break;
      case ComponentType.SELECT:
        imports.add('Select');
        break;
      case ComponentType.DATE_PICKER:
        imports.add('DatePicker');
        break;
    }
  });
  
  // 添加数据模型hook导入
  if (hooks.some(hook => hook.includes('use'))) {
    imports.add('useState');
    imports.add('useEffect');
  }
  
  // 生成服务导入
  const modelServices = Object.keys(modelMap)
    .filter(modelName => page.components.some((comp: any) => 
      comp.props.dataBinding?.model === modelName
    ));
    
  if (modelServices.length > 0) {
    imports.add(`{ ${modelServices.map(name => `get${name}List`).join(', ')} } from '@/services'`);
  }
  
  const importStatements = Array.from(imports)
    .map(imp => {
      if (imp === 'React') return `import React from 'react';`;
      if (imp.startsWith('{') && imp.endsWith('}')) return `import ${imp} from '@/services';`;
      return `import { ${imp} } from 'antd';`;
    })
    .join('\n');
  
  return formatCode(`
    ${importStatements}
    
    const ${page.name} = () => {
      ${hooks.join('\n      ')}
      
      return (
        <div style={{ padding: 24 }}>
          ${components.join('\n          ')}
        </div>
      );
    };
    
    export default ${page.name};
  `);
};

// 生成服务层代码
const generateServiceCode = (model: any) => {
  return formatCode(`
    import request from '@/utils/request';
    
    export async function get${model.name}List(params) {
      return request('/api/${model.name}', {
        method: 'GET',
        params,
      });
    }
    
    export async function create${model.name}(data) {
      return request('/api/${model.name}', {
        method: 'POST',
        data,
      });
    }
    
    export async function update${model.name}(id, data) {
      return request(\`/api/${model.name}/\${id}\`, {
        method: 'PUT',
        data,
      });
    }
    
    export async function delete${model.name}(id) {
      return request(\`/api/${model.name}/\${id}\`, {
        method: 'DELETE',
      });
    }
  `);
};

// 生成主应用代码
const generateAppCode = (pages: any[]) => {
  const pageRoutes = pages.map(page => `
    {
      path: '${page.path}',
      element: <${page.name} />,
    }
  `).join(',\n    ');
  
  return formatCode(`
    import React from 'react';
    import { BrowserRouter, Routes, Route } from 'react-router-dom';
    import { Layout, Menu } from 'antd';
    ${pages.map(page => `import ${page.name} from './pages/${page.name}';`).join('\n')}
    
    const { Header, Content } = Layout;
    
    const items = [
      ${pages.map(page => `{ key: '${page.path}', label: '${page.name}' }`).join(',\n      ')}
    ];
    
    function App() {
      return (
        <BrowserRouter>
          <Layout>
            <Header>
              <Menu 
                theme="dark" 
                mode="horizontal" 
                defaultSelectedKeys={['/']}
                items={items}
              />
            </Header>
            <Content style={{ padding: '24px 50px' }}>
              <Routes>
                <Route path="/" element={<${pages[0].name} />} />
                ${pageRoutes}
              </Routes>
            </Content>
          </Layout>
        </BrowserRouter>
      );
    }
    
    export default App;
  `);
};

// 生成项目
export const generateProject = () => {
  const { pages, models } = useStore.getState();
  const zip = new JSZip();
  
  // 创建项目结构
  const src = zip.folder('src');
  const pagesFolder = src?.folder('pages');
  const servicesFolder = src?.folder('services');
  const utilsFolder = src?.folder('utils');
  
  // 生成模型映射
  const modelMap: Record<string, any> = {};
  Object.values(models).forEach(model => {
    modelMap[model.name] = model;
  });
  
  // 生成页面代码
  Object.values(pages).forEach(page => {
    pagesFolder?.file(`${page.name}.tsx`, generatePageCode(page, modelMap));
  });
  
  // 生成服务代码
  Object.values(models).forEach(model => {
    servicesFolder?.file(`${model.name}Service.ts`, generateServiceCode(model));
  });
  
  // 生成工具文件
  utilsFolder?.file('request.ts', `
    import axios from 'axios';
    
    const request = axios.create({
      baseURL: 'http://localhost:3000',
      timeout: 5000,
    });
    
    request.interceptors.response.use(
      response => response.data,
      error => {
        console.error('请求错误:', error);
        return Promise.reject(error);
      }
    );
    
    export default request;
  `);
  
  // 生成主应用
  src?.file('App.tsx', generateAppCode(Object.values(pages)));
  
  // 生成入口文件
  src?.file('main.tsx', `
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    import 'antd/dist/reset.css';
    import './index.css';
    
    ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
  `);
  
  // 生成package.json
  zip.file('package.json', JSON.stringify({
    name: "generated-project",
    version: "1.0.0",
    scripts: {
      "dev": "vite",
      "build": "tsc && vite build",
      "preview": "vite preview"
    },
    dependencies: {
      "react": "^18.2.0",
      "react-dom": "^18.2.0",
      "antd": "^5.16.1",
      "axios": "^1.6.0",
      "react-router-dom": "^6.22.3"
    },
    devDependencies: {
      "@types/react": "^18.2.43",
      "@types/react-dom": "^18.2.17",
      "@vitejs/plugin-react": "^4.2.1",
      "typescript": "^5.2.2",
      "vite": "^5.1.0"
    }
  }, null, 2));
  
  // 生成tsconfig.json
  zip.file('tsconfig.json', JSON.stringify({
    "compilerOptions": {
      "target": "ES2020",
      "useDefineForClassFields": true,
      "lib": ["ES2020", "DOM", "DOM.Iterable"],
      "module": "ESNext",
      "skipLibCheck": true,
      "esModuleInterop": true,
      "moduleResolution": "Node",
      "resolveJsonModule": true,
      "isolatedModules": true,
      "noEmit": true,
      "jsx": "react-jsx"
    },
    "include": ["src"]
  }, null, 2));
  
  // 生成vite配置
  zip.file('vite.config.ts', `
    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    
    export default defineConfig({
      plugins: [react()],
    })
  `);
  
  // 生成README
  zip.file('README.md', `
    # 毕业设计项目
    
    ## 启动项目
    
    \`\`\`bash
    npm install
    npm run dev
    \`\`\`
    
    ## 项目结构
    
    - src/App.tsx: 主应用
    - src/pages/: 页面组件
    - src/services/: API服务
  `);
  
  return zip;
};

// 导出项目
export const exportProject = (projectName: string = '毕业设计项目') => {
  const zip = generateProject();
  zip.generateAsync({ type: 'blob' }).then((blob) => {
    saveAs(blob, `${projectName}.zip`);
  });
};